package in.co.codedoc.event;

import in.co.codedoc.cg.annotations.IsAnIOCComponent;
import in.co.codedoc.json.JSONUtil;
import in.co.codedoc.time.DayTime;

@IsAnIOCComponent
public class EventAsynchronizer
{
	@EventHandler
	public void Asynchronize(Object event)
	{
		String eventType = event.getClass().getCanonicalName();
		
		AsyncEventMeta aem = new AsyncEventMeta();
		
		aem.SetEventType(eventType);
		aem.SetPickedUpAt(null);
		DayTime schedule  = null; 
		
		if(event instanceof DelayedEvent)
		{
			schedule = new DayTime(((DelayedEvent)event).GetDelay()*1000);
		}
		else if(event instanceof ScheduledEvent)
		{
			schedule = ((ScheduledEvent)event).GetSchedule();
		}
		
		if(schedule != null)
		{
			if(schedule.compareTo(new DayTime()) < 0)
			{
				Logger.logger.error("Programming error! Scheduled time for the event '" + event.getClass() + "' is in the past. IGNORING and resetting to 'now'");
			}
			else
			{
				aem.SetEarliestNextPickup(schedule);
			}
		}
		aem.Save();
		
		AsyncEvent ae = new AsyncEvent();
		ae.SetEventData(JSONUtil.Encode(event, eventType).Encode());
		ae.SetMetaId(aem.GetId().GetId());
		ae.Save();
	}
}
